import React, { Component } from 'react';
import { Button, Drawer, Tree, message } from 'antd';
import { inject, observer } from 'mobx-react';
import { listModuleTree } from '../service/index';
import '../less/index.less';
import { createFromIconfontCN } from '@ant-design/icons';
const Icon = createFromIconfontCN({ scriptUrl: 'public/icon/all.js' });

@inject('store')
@observer
class ModuleDrawer extends Component {
  state = {
    moduleTree: [],
  };

  componentDidMount = async () => {
    this.setState({ moduleTree: await listModuleTree() });
  };

  onClose = () => {
    this.props.store.closeDrawer();
  };

  onConfirm = async () => {
    await this.props.store.updateRoleModule();
    message.info('授权成功！');
  };

  onCheck = checkedKeys => {
    this.props.store.checkModuleTree(checkedKeys);
  };
  loop = data => {
    return data.map((item) => {
      if (item.children && item.children.length > 0) {
        return {
          key: item.id,
          title: item.name,
          isLeaf: item.isLeaf,
          icon: <Icon type={item.icon}/>,
          children: this.loop(item.children),
        };
      }
      return { key: item.id, title: item.name, icon: <Icon type={item.icon}/>, isLeaf: item.isLeaf };
    });
  };

  render() {
    const { store } = this.props;
    let { role, moduleList, visible, loading, disabled } = store.moduleDrawerData;
    let title = (role ? role.name : '') + ' - 可访问资源';

    return (
      <Drawer title={title} visible={visible} width={500} closable={false} bodyStyle={{ padding: '5px 0px 50px 15px' }}
              onClose={this.onClose} destroyOnClose={true}>
        <Tree treeData={this.loop(this.state.moduleTree)} disabled={disabled} showIcon defaultExpandAll checkable checkedKeys={moduleList} onCheck={this.onCheck}/>
        <div className={'footer'}>
          <Button onClick={this.onClose} style={{ marginRight: 8 }}>返回</Button>
          <Button disabled={disabled} loading={loading} onClick={this.onConfirm} type="primary">保存</Button>
        </div>
      </Drawer>);
  }
}

export default ModuleDrawer;
